package com.xonro.common.histrans.zz.biz;

import com.actionsoft.bpms.bpmn.engine.model.def.ProcessDefinition;
import com.actionsoft.bpms.bpmn.engine.model.run.HistoryTaskInstanceModel;
import com.actionsoft.bpms.bpmn.engine.model.run.ProcessInstanceModel;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.service.model.TaskComment;
import com.alipay.sofa.common.profile.StringUtil;
import com.xonro.common.histrans.base.consts.MDMPROCESSSFLAG;
import com.xonro.common.histrans.zz.ctx.DrpProcessCreateContext;
import org.apache.commons.collections4.CollectionUtils;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:zhuw
 * @Description:
 * @Date 2022/4/25
 */
public class ProcessInfoBiz {
    private static ProcessInfoBiz processInfoBiz = new ProcessInfoBiz();

    public static ProcessInfoBiz getInstance() {
        return processInfoBiz;
    }

    public void addProcessInfo(String processDefId, String startActivityDefId, String title,
                                String code, DrpProcessCreateContext processCreateContext) {
        ProcessDefinition processDefinition = SDK.getRepositoryAPI().getProcessDefinition(processDefId);
        String ccId = processCreateContext.getCcId();
//        List<RowMap> oaProcessList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM Tb_BillMaster WHERE billCode = ? AND enCode = ?", billCode, code);
        List<RowMap> oaProcessList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM f2bpm_hi_processinstance WHERE   WorkflowInstanceId = ?",  code);
        boolean isProcessEnd;
        String processStatus;
        ProcessInstanceModel processInstance = new ProcessInstanceModel();
        if (CollectionUtils.isNotEmpty(oaProcessList)) {//历史流程中有数据就是完成了
            if (StringUtil.equals("3", oaProcessList.get(0).getString("WorkflowInstanceState"))) {
                isProcessEnd = true;
                processStatus = MDMPROCESSSFLAG.END;
                processInstance.setEnd(true);
                processInstance.setControlState("end");
            } else {
                isProcessEnd = false;
                processStatus = MDMPROCESSSFLAG.DRAFT;
                processInstance.setEnd(false);
            }
        }else {
            isProcessEnd = false;
            processStatus = MDMPROCESSSFLAG.DRAFT;
            processInstance.setEnd(false);
        }
//        List<RowMap> oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM tb_BillFlow WHERE billCode = ? AND enCode = ?", billCode, code);
        List<RowMap> oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT act.*,task.Opinion,def.ActivityName FROM f2bpm_hi_activityinstance act " +
                "LEFT JOIN f2bpm_hi_taskinstance task ON act.ActivityInstanceId=task.ActivityInstanceId " +
                "LEFT JOIN f2bpm_activity def on def.ActivityId=act.ActivityId WHERE act.WorkflowInstanceId = ? ", code);

       /* List<RowMap> oaCommentCopyList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT act.*,task.Opinion,def.ActivityName FROM f2bpm_hi_activityinstance act " +
                "LEFT JOIN f2bpm_hi_taskinstance_copy1 task ON act.ActivityInstanceId=task.ActivityInstanceId " +
                "LEFT JOIN f2bpm_activity def on def.ActivityId=act.ActivityId WHERE act.WorkflowInstanceId = ? ", code);
        if(oaCommentList.size()<oaCommentCopyList.size()){
            oaCommentList=oaCommentCopyList;
        }*/

        if (CollectionUtils.isEmpty(oaProcessList)) {
//            oaProcessList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM Tb_BillMaster_H WHERE billCode = ? AND enCode = ?", billCode, code);
            oaProcessList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM f2bpm_processinstance WHERE  WorkflowInstanceId = ?", code);
            if (CollectionUtils.isEmpty(oaProcessList)) {

                processCreateContext.setHasProcess(false);
                return;
            }
        }
        if (CollectionUtils.isEmpty(oaCommentList)) {
//            oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM tb_BillFlow_H WHERE billCode = ? AND enCode = ?", billCode, code);
            oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT act.*,task.Opinion,def.ActivityName FROM f2bpm_activityinstance act " +
                    "LEFT JOIN f2bpm_taskinstance task ON act.ActivityInstanceId=task.ActivityInstanceId " +
                    "LEFT JOIN f2bpm_activity def on def.ActivityId=act.ActivityId WHERE act.WorkflowInstanceId = ? ", code);
        }
        RowMap oaProcess = oaProcessList.get(0);

        packInstance(startActivityDefId, title, processCreateContext, processDefinition, isProcessEnd, processStatus, processInstance, oaCommentList, oaProcess);
    }


    public void addProcessInfoDrp1(String processDefId, String startActivityDefId, String title,
                               String code, DrpProcessCreateContext processCreateContext) {
        ProcessDefinition processDefinition = SDK.getRepositoryAPI().getProcessDefinition(processDefId);
        String ccId = processCreateContext.getDrp1CCId();//drp1.0查询 workflow表
//        List<RowMap> oaProcessList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM Tb_BillMaster WHERE billCode = ? AND enCode = ?", billCode, code);
       RowMap oaProcess= SDK.getCCAPI().getRDSAPI(ccId).getMap("SELECT * FROM WFI_FlowToken WHERE   TokenName = ?",  code);
        boolean isProcessEnd;
        String processStatus;
        ProcessInstanceModel processInstance = new ProcessInstanceModel();
        if (oaProcess!=null&&oaProcess.size()>0) {
            if (StringUtil.isNotEmpty(oaProcess.getString("EndTime"))) {//WFI_FlowToken中有数据，并且有结束时间的是已完成的数据
                isProcessEnd = true;
                processStatus = MDMPROCESSSFLAG.END;
                processInstance.setEnd(true);
                processInstance.setControlState("end");
            } else {
                isProcessEnd = false;
                processStatus = MDMPROCESSSFLAG.DRAFT;
                processInstance.setEnd(false);
            }
        }
            else {
                return;
            }
//        List<RowMap> oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM tb_BillFlow WHERE billCode = ? AND enCode = ?", billCode, code);
        List<RowMap> oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * from WFI_ActorToken WHERE WorkflowTokenId = ? ", oaProcess.getString("ID"));

       /* List<RowMap> oaCommentCopyList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT act.*,task.Opinion,def.ActivityName FROM f2bpm_hi_activityinstance act " +
                "LEFT JOIN f2bpm_hi_taskinstance_copy1 task ON act.ActivityInstanceId=task.ActivityInstanceId " +
                "LEFT JOIN f2bpm_activity def on def.ActivityId=act.ActivityId WHERE act.WorkflowInstanceId = ? ", code);
        if(oaCommentList.size()<oaCommentCopyList.size()){
            oaCommentList=oaCommentCopyList;
        }*/


        if (CollectionUtils.isEmpty(oaCommentList)) {
//            oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM tb_BillFlow_H WHERE billCode = ? AND enCode = ?", billCode, code);
            oaCommentList = SDK.getCCAPI().getRDSAPI(ccId).getMaps("SELECT * FROM f2bpm_taskinstance WHERE  WorkflowInstanceId = ?",  code);
        }

        packInstance1(startActivityDefId, title, processCreateContext, processDefinition, isProcessEnd, processStatus, processInstance, oaCommentList, oaProcess);
    }

    private void packInstance(String startActivityDefId, String title, DrpProcessCreateContext processCreateContext, ProcessDefinition processDefinition, boolean isProcessEnd, String processStatus, ProcessInstanceModel processInstance, List<RowMap> oaCommentList, RowMap oaProcess) {
        processCreateContext.getProcessCreateContext().setProcessStatus(processStatus);
        processInstance.setId(UUIDGener.getUUID());
        // processInstance.setCreateUser(getUserExchange(CommTransBiz.getInstance().getUserId(oaProcess.getString("Creator"))));
        // processInstance.setCreateUser(oaProcess.getString("Creator"));//
        processInstance.setCreateUser("admin");//

        processInstance.setTitle(title);
        processInstance.setTrash(false);
        processInstance.setProcessBusinessKey(UUIDGener.getUUID());
        processInstance.setProcessDefVerId(processDefinition.getVersionId());
        processInstance.setProcessDefId(processDefinition.getId());
        processInstance.setProcessGroupId(processDefinition.getProcessGroupId());
        processInstance.setCreateTime(new Timestamp(oaProcess.getDate("StartedTime").getTime()));
        processInstance.setStartTime(new Timestamp(oaProcess.getDate("StartedTime").getTime()));
        processInstance.setStartActivityId(startActivityDefId);
        processCreateContext.getProcessCreateContext().setProcessInstanceModel(processInstance);
        //  if (isProcessEnd) {
        List<HistoryTaskInstanceModel> taskInstanceModels = new ArrayList<>();
        processCreateContext.getProcessCreateContext().setHistoryTaskInstanceModels(taskInstanceModels);
        HistoryTaskInstanceModel taskInstance = new HistoryTaskInstanceModel();
        taskInstanceModels.add(taskInstance);
        taskInstance.setId(UUIDGener.getUUID());
        taskInstance.setActivityDefId(startActivityDefId);
        taskInstance.setProcessInstId(processInstance.getId());
        taskInstance.setProcessDefId(processInstance.getProcessDefId());
        taskInstance.setProcessDefVerId(processInstance.getProcessDefVerId());
        taskInstance.setProcessGroupId(processInstance.getProcessGroupId());
        taskInstance.setTitle(processInstance.getTitle());
        taskInstance.setBeginTime(processInstance.getCreateTime());
        taskInstance.setEndTime(processInstance.getCreateTime());
        taskInstance.setControlState("complete");
        taskInstance.setTarget(getUserExchange(processInstance.getCreateUser()));
        taskInstance.setOwner(getUserExchange(processInstance.getCreateUser()));
        taskInstance.setParentTaskInstId("00000000-0000-0000-0000-000000000000");
        taskInstance.setScopeId("00000000-0000-0000-0000-000000000000");
        List<TaskComment> taskComments = new ArrayList<>();
        processCreateContext.getProcessCreateContext().setTaskHistoryCommentModels(taskComments);
        Date processEndDate = processInstance.getStartTime();
        for (RowMap oaComment : oaCommentList) {
            TaskComment taskComment = new TaskComment();
            taskComments.add(taskComment);
            taskComment.setId(UUIDGener.getUUID());
            taskComment.setProcessInstId(processInstance.getId());
            taskComment.setTaskInstId(taskInstance.getId());
            taskComment.setCreateDate(new Timestamp(oaComment.getDate("CreatedTime").getTime()));
            taskComment.setCreateUser(oaComment.getString("UserName"));
            taskComment.setActivityName(oaComment.getString("ActivityName"));
            taskComment.setActionName(oaComment.getString("FinishedCommand"));
            taskComment.setMsg(oaComment.getString("Opinion"));
        }
        processInstance.setEndTime(new Timestamp(processEndDate.getTime()));
        processInstance.setEndActivityId(startActivityDefId);

    }

    private void packInstance1(String startActivityDefId, String title, DrpProcessCreateContext processCreateContext, ProcessDefinition processDefinition, boolean isProcessEnd, String processStatus, ProcessInstanceModel processInstance, List<RowMap> oaCommentList, RowMap oaProcess) {
        processCreateContext.getProcessCreateContext().setProcessStatus(processStatus);
        processInstance.setId(UUIDGener.getUUID());
        // processInstance.setCreateUser(getUserExchange(CommTransBiz.getInstance().getUserId(oaProcess.getString("Creator"))));
        // processInstance.setCreateUser(oaProcess.getString("Creator"));//
        processInstance.setCreateUser("admin");//

        processInstance.setTitle(title);
        processInstance.setTrash(false);
        processInstance.setProcessBusinessKey(UUIDGener.getUUID());
        processInstance.setProcessDefVerId(processDefinition.getVersionId());
        processInstance.setProcessDefId(processDefinition.getId());
        processInstance.setProcessGroupId(processDefinition.getProcessGroupId());
        processInstance.setCreateTime(new Timestamp(oaProcess.getDate("StartTime").getTime()));
        processInstance.setStartTime(new Timestamp(oaProcess.getDate("StartTime").getTime()));
        processInstance.setStartActivityId(startActivityDefId);
        processCreateContext.getProcessCreateContext().setProcessInstanceModel(processInstance);
        //  if (isProcessEnd) {
        List<HistoryTaskInstanceModel> taskInstanceModels = new ArrayList<>();
        processCreateContext.getProcessCreateContext().setHistoryTaskInstanceModels(taskInstanceModels);
        HistoryTaskInstanceModel taskInstance = new HistoryTaskInstanceModel();
        taskInstanceModels.add(taskInstance);
        taskInstance.setId(UUIDGener.getUUID());
        taskInstance.setActivityDefId(startActivityDefId);
        taskInstance.setProcessInstId(processInstance.getId());
        taskInstance.setProcessDefId(processInstance.getProcessDefId());
        taskInstance.setProcessDefVerId(processInstance.getProcessDefVerId());
        taskInstance.setProcessGroupId(processInstance.getProcessGroupId());
        taskInstance.setTitle(processInstance.getTitle());
        taskInstance.setBeginTime(processInstance.getCreateTime());
        taskInstance.setEndTime(processInstance.getCreateTime());
        taskInstance.setControlState("complete");
        taskInstance.setTarget(getUserExchange(processInstance.getCreateUser()));
        taskInstance.setOwner(getUserExchange(processInstance.getCreateUser()));
        taskInstance.setParentTaskInstId("00000000-0000-0000-0000-000000000000");
        taskInstance.setScopeId("00000000-0000-0000-0000-000000000000");
        List<TaskComment> taskComments = new ArrayList<>();
        processCreateContext.getProcessCreateContext().setTaskHistoryCommentModels(taskComments);
        Date processEndDate = processInstance.getStartTime();
        for (RowMap oaComment : oaCommentList) {
            TaskComment taskComment = new TaskComment();
            taskComments.add(taskComment);
            taskComment.setId(UUIDGener.getUUID());
            taskComment.setProcessInstId(processInstance.getId());
            taskComment.setTaskInstId(taskInstance.getId());
            taskComment.setCreateDate(new Timestamp(oaComment.getDate("CreateTime").getTime()));
            taskComment.setCreateUser(oaComment.getString("ActorName"));
            taskComment.setActivityName(oaComment.getString("NodeName"));
            taskComment.setActionName(oaComment.getString("DoResult"));
            taskComment.setMsg(oaComment.getString("DoDesc"));
        }
        processInstance.setEndTime(new Timestamp(processEndDate.getTime()));
        processInstance.setEndActivityId(startActivityDefId);

    }


    public void addRecordProcessInfo(String processDefId, String startActivityDefId, String title, DrpProcessCreateContext processCreateContext){
        ProcessDefinition processDefinition = SDK.getRepositoryAPI().getProcessDefinition(processDefId);
        ProcessInstanceModel processInstance = new ProcessInstanceModel();
        Timestamp createTime = new Timestamp(new Date().getTime());
        processCreateContext.getProcessCreateContext().setProcessStatus(MDMPROCESSSFLAG.END);
        processInstance.setId(UUIDGener.getUUID());
        processInstance.setCreateUser("admin");
        processInstance.setTitle(title);
        processInstance.setTrash(false);
        processInstance.setProcessBusinessKey(UUIDGener.getUUID());
        processInstance.setProcessDefVerId(processDefinition.getVersionId());
        processInstance.setProcessDefId(processDefinition.getId());
        processInstance.setProcessGroupId(processDefinition.getProcessGroupId());
        processInstance.setCreateTime(createTime);
        processInstance.setStartTime(createTime);
        processInstance.setStartActivityId(startActivityDefId);
        processCreateContext.getProcessCreateContext().setProcessInstanceModel(processInstance);
    }


    private  String getUserExchange(String oaUserId) {
        return oaUserId;
    }

}
